package com.bangcommunity.bbframe.dynconfig;

import com.bangcommunity.bbframe.client.zookeeper.ZKClient;
import com.bangcommunity.bbframe.common.utils.id.DangDangIdFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;

import java.io.IOException;

/**
 * Created by tanghc on 17/8/26.
 */
public class LeaderSelectorTest2 {
    private static final String PATH = "/LeaderSelectorTest/leader";
    private static final String uid = "2222-" + DangDangIdFactory.getInstance().getIdGenerator("uid").generateId();

    public static void main(String[] args) throws IOException {
        CuratorFramework client = ZKClient.getClient();
        LeaderSelector leaderSelector = new LeaderSelector(client, PATH, new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                System.out.println(uid + ":I am leader.");
                Thread.sleep(2000);
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                System.out.println(uid + ":stateChanged." + newState);
            }
        });
        leaderSelector.autoRequeue();
        leaderSelector.start();

        System.in.read();

    }
}
